<template>
  <div class="app-container">
    <h3>Wangeditor富文本</h3>
    <div ref="editor"></div>
    <el-button size="small" type="primary" @click="submit" style="margin-top: 10px">提交</el-button>
    <div v-html="listHtml"></div>
  </div>
</template>

<script>
  import WangEditor from "wangeditor";
  import { onBeforeUnmount, onMounted, reactive, ref, toRefs } from "vue";
  import { localGet, uploadImgServer, uploadImgsServer, hasEmoji } from "@/utils";
  export default {
    name: "Weditor",
    components: {
      // Wangeditor,
    },
    setup() {
      const editor = ref(null);
      const state = reactive({
        listHtml: "",
      });
      let instance;
      onMounted(() => {
        instance = new WangEditor(editor.value);
        instance.config.showLinkImg = false;
        instance.config.showLinkImgAlt = false;
        instance.config.showLinkImgHref = false;
        instance.config.uploadImgMaxSize = 2 * 1024 * 1024; // 2M
        instance.config.uploadFileName = "file";
        instance.config.uploadImgHeaders = {
          token: state.token,
        };
        // 图片返回格式不同，需要自定义返回格式
        instance.config.uploadImgHooks = {
          // / 图片上传并返回了结果，想要自己把图片插入到编辑器中
          // 例如服务器端返回的不是 { errno: 0, data: [...] } 这种格式，可使用 customInsert
          customInsert: function (insertImgFn, result) {
            console.log(result);
            // result 即服务端返回的接口
            // insertImgFn 可把图片插入到编辑器，传入图片 src ，执行函数即可
            if (result.data && result.data.length) {
              result.data.forEach((item) => insertImgFn(item));
            }
          },
        };
        instance.config.uploadImgServer = uploadImgsServer;
        Object.assign(instance.config, {
          onchange() {
            console.log("change");
          },
        });
        instance.create();
      });
      const submit = () => {
        console.log("ada");
        console.log(instance.txt.html());
        state.listHtml = instance.txt.html();
      };
      onBeforeUnmount(() => {
        instance.destroy();
        instance = null;
      });
      return {
        ...toRefs(state),
        editor,
        submit,
      };
    },
  };
</script>
